#!/usr/bin/python2.7
#coding=utf8
import datetime

def merge_into_table(index, dec_fields, value, session):
    tablename = dec_fields[1]
    index = index.split(',')[0]
    date = dec_fields[0].split(',')[2]
    # print(tablename)
    sql ="select date from %s where date=%s" % (tablename, date)
    data = session.execute(sql).fetchall()
    # print(data)
    # print('\n\n\n')
    if data is None:
        sql = """
        insert into %s(date, %s, create_time, update_time) values (%s, %f, sysdate(), sysdate())
        """ % (tablename, index, date, float(value))
        # print(sql)
        session.execute(sql,None)
        session.commit()
    else:
        sql = """
                update %s set %s = %f , update_time = sysdate() where date=%s
                """ % (tablename, index, float(value), date)
        # print(sql)
        session.execute(sql,None)
        session.commit()


def merge_list_into_table(index, dec_fields, cell_value, session):
    tablename = dec_fields[1]
    index = index.split(',')[0]
    print(len(cell_value))
    for date_ls in cell_value:
        dates = date_ls.keys()
        for date in dates:
            sql = "select date from %s where date=%s" % (tablename, date)
            data = session.execute(sql).fetchone()
            # print(data)
            # print('\n\n\n')
            if date_ls[date] == '':
                date_ls[date] = 0.0
            if data is None:
                # print(date_ls[date],'xx')
                sql = """
                    insert into %s(date, %s, create_time, update_time) values (%s, %f, sysdate(), sysdate())
                    """ % (tablename, index, date, float(date_ls[date]))
                # print(sql)
                session.execute(sql,None)
            else:
                # print(date_ls[date])
                sql = """
                            update %s set %s = %f , update_time = sysdate() where date=%s
                            """ % (tablename, index, float(date_ls[date]), date)
                # print(sql)
                session.execute(sql,None)
            session.commit()